package com.fll.fangyicommon.utils;

import com.aliyun.oss.OSSClient;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author fll
 * @create 2023/2/24
 */
@Slf4j
public class OssUtil {

    //这里的配置可以在properties或者yml中进行配置
    private static String accessKeyId = "LTAI5tPvCU4JfL3K6CwV21Xc";

    private static String accessKeySecret = "2kGcMgYuTO1gowEfZvQUN3bhwYqh5G";

    private static String bucketName = "fangyi-img";

    private  static String  endPoint = "oss-cn-shenzhen.aliyuncs.com" ;

    private static String baseUrl = "https://fangyi-img.oss-cn-shenzhen.aliyuncs.com/";

    /**
     * 根据原始文件名生成时间文件名
     * @param fileName
     * @param userId
     * @return
     */
    public static String genName(String fileName, Integer userId) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        return format.format(new Date().getTime()) + "_" + userId + fileName.substring(fileName.lastIndexOf("."));
    }

    /**
     * 根据原始文件名生成时间文件名
     * @param fileName
     * @param userId
     * @return
     */
    public static String genName(String fileName, Integer userId, String task) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        return format.format(new Date().getTime()) + "_" + userId + "_" + task + fileName.substring(fileName.lastIndexOf("."));
    }


    //文件直接上传的方式，filename 为定义的文件名字
    public static String upload(File obj, String fileName) {
        OSSClient ossClient = null;
        try {
            ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
            ossClient.putObject(bucketName, fileName, obj);
            log.info("文件上传成功==> baseUrl:{} <==> fileName: {}", baseUrl, fileName);
            return baseUrl + fileName;
        } catch (Exception e) {
            e.printStackTrace();
            log.info("文件上传失败==> error:{}", e);
            return null;
        } finally {
            if (ossClient != null){
                ossClient.shutdown();
            }
        }
    }


    //文件字节方式进行上传，filename 为定义的文件名字
    public static String upload(byte[] array, String fileName) {
        OSSClient ossClient = null;
        try {
            ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
            ossClient.putObject(bucketName, fileName, new ByteArrayInputStream(array));
            log.info("文件上传成功==> baseUrl:{} <==> fileName: {}", baseUrl, fileName);
            return baseUrl + fileName;
        } catch (Exception e) {
            e.printStackTrace();
            log.info("文件上传失败==> error:{}", e);
            return null;
        } finally {
            if (ossClient != null){
                ossClient.shutdown();
            }
        }
    }


}
